package com.zhangxiaofanfan.hotcode.fourth.third;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-05-24 10:59:16
 */
public class HotCode014 {
    public static void main(String[] args) {
        int[][] intervals = {
                {1, 3},
                {2, 6},
                {8, 15},
                {15, 18}
        };
        HotCode014 hotCode014 = new HotCode014();
        Arrays.stream(hotCode014.merge(intervals)).forEach(nums -> System.out.println(Arrays.toString(nums)));
    }

    public int[][] merge(int[][] intervals) {
        if (intervals.length == 1) {
            return intervals;
        }
        Arrays.sort(intervals, Comparator.comparingInt(interval -> interval[0]));
        List<int[]> list = new ArrayList<>();
        int left = intervals[0][0], right = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            if (right < intervals[i][0]) {
                list.add(new int[] {left, right});
                left = intervals[i][0];
                right = intervals[i][1];
            } else {
                right = Math.max(intervals[i][1], right);
            }
        }
        list.add(new int[] {left, right});
        int[][] result = new int[list.size()][2];
        for (int i = 0; i < result.length; i++) {
            result[i][0] = list.get(i)[0];
            result[i][1] = list.get(i)[1];
        }
        return result;
    }
}
